/**
 * 首页管理
 */
var MainPage = {
    index: $("#content .page1"),
    current: $("#content .page1")
};
var $myInfoPrivilegeListTable;
var IndexMgr = {

    init: function () {

        IndexMgr.initMainPage();
        //
        $("#areaId").change(function (e) {
            init_app_id_mult_sbox('areaId', 'appId');
        });

        //保存权限
        $("#save_privilege_btn").click(function (e) {
            e.preventDefault();
            //
            if (is_invalid_form("add_privilege_form")) {
                return;
            }
            let params = {};
            params.loginUser = $("#loginUser").val();
            params.areaId = $("#areaId").val();
            params.appId = $("#appId").val();
            params.appName = $("#appId option:selected").html().split("-")[1];
            params.description = $("#description").val();
            $.ajax({
                url: ApiConfig.PRIVILEGE_SAVE,
                type: "post",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(params)
            }).done(function (resp) {
                if (resp.status == 0) {
                    alert_tip("提示", "保存成功！");
                    $("#add_privilege_modal").modal("hide");
                    //
                    IndexMgr.reloadPrivilegeListTable();
                } else {
                    alert_tip("提示", resp.message);
                }
            })
        });
    },

    initMainPage: function () {
        $(".logo_img").css("background", "url(./img/logo_03.png) no-repeat center");
        //
        IndexMgr.initIndexAreaId();
        //
        //左侧-导航菜单加载不同页面
        $(".home_menu .menu-option").click(function (e) {
            e.preventDefault();

            $(".home_menu .menu-option").removeClass('active');
            $(this).addClass('active');
            var src = $(this).attr("page");
            MainPage.current.attr("src", src);
        });

        //左上角-[自动化测试系统]
        $(".logo a").click(function () {
            let li_list = $("#js-left-menu li");
            for (let i = 0; i < li_list.length; i++) {
                let item = $(li_list[i]);
                item.removeClass("bg_e8ebf0Color");
                item.removeClass("hasClick");
                item.removeClass("bg_c6cbd4Color");
                item.find("a").removeClass("active");
            }
            MainPage.current.attr("src", ApiConfig.DASHBOARD_ZDO);
        });

        //右上角-[退出]
        $("#quit").click(function (e) {
            e.preventDefault();
            // s1:
            let areaId = get_area_id_from_session();
            // s2:
            sessionStorage.removeItem(ApiConfig.SESSION_INDEX_AREA_ID);
            sessionStorage.removeItem(ApiConfig.SESSION_INDEX_AREA_ID_NAME);
            window.location = ApiConfig.BIZ_LOGOUT + "&areaId=" + areaId;
        });

        //右上角-[我的]
        $("#my_info").click(function (e) {
            e.preventDefault();
            $("#pri_search_login_user").val("");
            //
            if ($myInfoPrivilegeListTable) {
                IndexMgr.reloadPrivilegeListTable();
                $("#my_info_modal").modal("show");
                return;
            }
            $myInfoPrivilegeListTable = $("#my_info_privilege_list_table").bootstrapTable({
                url: ApiConfig.PRIVILEGE_LIST,
                queryParams: function (queryParam) {
                    let params = {};
                    params.offset = queryParam.pageSize * (queryParam.pageNumber - 1);
                    params.limit = queryParam.pageSize;
                    params.loginUser = $(".userName").html();
                    //
                    let searchVal = $("#pri_search_login_user").val() || null;
                    if (searchVal != null) {
                        params.loginUser = searchVal;
                    }
                    return params;
                },
                queryParamsType: 'no',
                method: 'post',
                contentType: 'application/json',
                dataType: 'json',
                pageNumber: 1,
                pageSize: 10,
                pageList: [10, 20, 50, 100],
                sidePagination: 'server',
                pagination: true,
                smartDisplay: true,
                responseHandler: function (resp) {
                    if (resp.status === 0) {
                        var dto = {};
                        dto.total = 0 || resp.content.total;
                        dto.rows = resp.content.rows || [];
                        set_row_btn_permission(dto.rows, resp.content.display);
                        return dto;
                    } else {
                        return {
                            total: 0,
                            rows: []
                        }
                    }
                },
                rowStyle: function (row, index) {
                    var classes = ['info'];
                    if (index % 2 === 0) {
                        return {
                            classes: classes[0]
                        };
                    } else {
                        return {};
                    }
                },
                columns: [{
                    field: 'id',
                    title: '序号',
                    formatter: function (value, row, index) {
                        index = index + 1;
                        return index;
                    }
                }, {
                    field: 'id',
                    title: 'ID',
                    class: 'hidden'
                }, {
                    field: 'createTime',
                    title: '创建时间',
                    formatter: function (value, row, index) {
                        return date_format(value);
                    }
                }, {
                    field: 'loginUser',
                    title: '登录用户'
                }, {
                    field: 'areaId',
                    title: '区域编号'
                }, {
                    field: 'appId',
                    title: '应用编号'
                }, {
                    field: 'appName',
                    title: '应用名称'
                }, {
                    field: 'description',
                    title: '描述',
                    align: 'left'
                }, {
                    field: 'operate',
                    title: '操作',
                    align: 'center',
                    events: {
                        'click #clear_privilege_btn': function (e, value, row, index) {
                            e.preventDefault();
                            IndexMgr.clearUserPrivilege(e, value, row, index);
                        }
                    },
                    formatter: function (value, row, index) {
                        if (row.btn_display) {
                            return `<button class='btn btn-primary ' id="clear_privilege_btn" >清除</button>`;
                        }
                        return "";
                    }
                }]
            });
            $("#my_info_modal").modal("show");
        });

        //右上角-[我的]-查询
        $(".search_login_user_btn").click(function (e) {
            e.preventDefault();
            IndexMgr.reloadPrivilegeListTable();
        });

        //右上角-[我的]-重置
        $(".reset_login_user_btn").click(function (e) {
            e.preventDefault();
            $("#pri_search_login_user").val("");
            //
            $(".search_login_user_btn").click();
        });

        //右上角-[我的]-新增
        $(".add_privilege_btn").click(function (e) {
            e.preventDefault();
            $("#loginUser").val("");
            $("#areaId").val("");
            $("#appId").val("");
            //
            init_all_area_and_app_sbox("areaId", "appId");
            $("#add_privilege_modal").modal("show");
        });

        //表单校验
        $('#add_privilege_form').bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            excluded: [':disabled'],
            fields: {
                loginUser: {
                    validators: {
                        notEmpty: {
                            message: '登录用户不能为空！'
                        },
                        stringLength: {
                            min: 4,
                            max: 200,
                            message: '长度为4至200个字符！'
                        }
                    }
                },
                areaId: {
                    validators: {
                        notEmpty: {
                            message: '所属区域不能为空！'
                        }
                    }
                },
                appId: {
                    validators: {
                        notEmpty: {
                            message: '应用编号不能为空！'
                        },
                        stringLength: {
                            min: 4,
                            max: 16,
                            message: '长度为4至16个字符！'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z-_]+$/,
                            message: '只能包含-或_或字母！'
                        }
                    }
                },
                description: {
                    validators: {
                        stringLength: {
                            min: 0,
                            max: 100,
                            message: '长度最大为100个字符！'
                        }
                    }
                }
            }
        });

        //下拉菜单
        $('.zz-side-nav-item').each(function (index, item) {
            $(item).click(function (e) {
                if ($(e.target).hasClass("zz-firstLink") || $(e.target).hasClass("zz-arrowUp") || $(e.target).hasClass("zz-arrowDown") || $(e.target.parentNode).hasClass('zz-firstLink')) {

                    if ($('.hasClick').hasClass("zz-side-nav-item")) {
                        $('.hasClick').addClass("bg_e8ebf0Color").removeClass("bg_c6cbd4Color hasClick");
                    } else if ($('.hasClick').hasClass("zz-sideNav-dropMenuItem")) {
                        $('.hasClick').parents(".zz-side-nav-item").addClass("bg_e8ebf0Color").removeClass("bg_c6cbd4Color");
                        $('.hasClick').removeClass("zz-sideNav-dropMenuItem-hasClicked hasClick");

                    }
                    $(this).attr("data-index", index).addClass("hasClick");
                    $(this).addClass("bg_c6cbd4Color").siblings().removeClass("bg_e8ebf0Color")
                    $arrowToggle = $(this).find('i');
                    var slideTime = $(this).find(".zz-sideNav-dropMenu").find('.zz-sideNav-dropMenuItem').length * 25;
                    if ($arrowToggle.hasClass('zz-arrowDown')) {
                        $arrowToggle.removeClass('zz-arrowDown').addClass('zz-arrowUp')
                        $(this).find(".zz-sideNav-dropMenu").slideDown(slideTime).parent().siblings().find(".zz-sideNav-dropMenu").slideUp(slideTime);
                        $(this).siblings().find("i").removeClass('zz-arrowUp').addClass('zz-arrowDown');
                        if (!$(this).find(".zz-sideNav-dropMenu").length) {//没有子菜单
                            $(this).siblings().find(".zz-sideNav-dropMenu").slideUp(slideTime);
                        }
                    } else if ($arrowToggle.hasClass('zz-arrowUp')) {
                        $arrowToggle.removeClass('zz-arrowUp').addClass('zz-arrowDown')
                        $(this).find(".zz-sideNav-dropMenu").slideUp(slideTime).parent().siblings().find(".zz-sideNav-dropMenu").slideUp(slideTime);
                        if (!$(this).find(".zz-sideNav-dropMenu").length) {//没有子菜单
                            $(this).siblings().find(".zz-sideNav-dropMenu").slideUp(slideTime);
                        }
                    }
                } else if ($(e.target).hasClass('zz-secondLink')) {
                    if ($('.hasClick').hasClass("zz-side-nav-item")) {
                        $('.hasClick').removeClass("bg_e8ebf0Color bg_c6cbd4Color hasClick");
                    } else if ($('.hasClick').hasClass("zz-sideNav-dropMenuItem")) {
                        $('.hasClick').removeClass("zz-sideNav-dropMenuItem-hasClicked hasClick");
                    }

                    $(e.target).parent(".zz-sideNav-dropMenuItem").attr("data-index", index).addClass("zz-sideNav-dropMenuItem-hasClicked").addClass("hasClick")
                    $(e.target).parent(".zz-sideNav-dropMenuItem").parents(".zz-side-nav-item").addClass("bg_c6cbd4Color");
                    //$(e.target).parent("li").siblings().find('.zz-secondLink').css({"color":"#354052"})
                }
                $(this).siblings().find(".zz-sideNav-dropMenu").slideUp(slideTime);
                $(this).siblings().find('i').removeClass('zz-arrowUp').addClass('zz-arrowDown');
            })
        });

        $(".leftBtn").click(function () {
            $("#js-left-menu").hide();
            $("#js-right-menu").css("left", 0);
            $("#content").css("padding-left", "40px");
            $(".jsh_nav").css("width", "40px")
        });

        $("#js-right-menu").click(function () {
            $("#js-left-menu").show();
            $("#js-right-menu").css("left", "-40px");
            $("#content").css("padding-left", "216px");
            $(".jsh_nav").css("width", "216px")
        });
    },

    initIndexAreaId: function () {
        let params = {};
        $.ajax({
            url: ApiConfig.LOGIN_USER_AREALIST,
            type: "post",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(params)
        }).done(function (resp) {
            if (resp.status == 0) {
                let area_list = resp.content;
                $("#index_area_id_ul li").remove();
                for (var i = 0; i < area_list.length; i++) {
                    $("#index_area_id_ul").append(`<li role="presentation">
                    <a style="min-width: 120px; text-align: left; padding-left: 6px;" role="menuitem" tabindex="-1" href="#" onclick="IndexMgr.clickIndexAreaId('${area_list[i].areaId}', '${area_list[i].areaName}')">${area_list[i].areaId}-${area_list[i].areaName}</a>
                </li>`);
                }
                let cur_area_info = sessionStorage.getItem(ApiConfig.SESSION_INDEX_AREA_ID_NAME);
                if (cur_area_info != "" && cur_area_info != null) {
                    $("#index_area_id_btn").html(`${cur_area_info} <span class="caret"></span>`);
                } else {
                    cur_area_info = $($("#index_area_id_ul").find("a")[0]).html();
                    $("#index_area_id_btn").html(`${cur_area_info} <span class="caret"></span>`);
                    sessionStorage.setItem(ApiConfig.SESSION_INDEX_AREA_ID, cur_area_info.split("-")[0]);
                    sessionStorage.setItem(ApiConfig.SESSION_INDEX_AREA_ID_NAME, cur_area_info);
                }
                MainPage.current.attr("src", ApiConfig.DASHBOARD_ZDO);
            } else {
                MainPage.current.attr("src", ApiConfig.NO_PERMISSION_ZDO);
            }
        })
    },

    clearUserPrivilege: function (e, value, row, index) {
        $.confirm({
            title: '提示',
            content: '是否确认清除？',
            buttons: {
                confirm: {
                    text: "确定",
                    btnClass: "btn btn-danger",
                    action: function () {
                        let params = {};
                        params.id = row.id;
                        $.ajax({
                            url: ApiConfig.PRIVILEGE_CLEAR,
                            type: "post",
                            dataType: "json",
                            contentType: "application/json",
                            data: JSON.stringify(params)
                        }).done(function (resp) {
                            if (resp.status == 0) {
                                alert_tip("提示", "清除成功！");
                                IndexMgr.reloadPrivilegeListTable();
                            } else {
                                alert_tip("提示", resp.message);
                            }
                        });
                    }
                },
                cancel: {
                    text: "取消",
                    btnClass: "btn btn-primary",
                    action: function () {
                    }
                }
            }
        });
    },

    reloadPrivilegeListTable: function () {
        let params = {};
        params.loginUser = $("#pri_search_login_user").val() || null;
        if (params.loginUser == null) {
            params.loginUser = $(".userName").html();
        }
        if ($myInfoPrivilegeListTable) {
            $myInfoPrivilegeListTable.bootstrapTable("refresh", {query: params, url: ApiConfig.PRIVILEGE_LIST});
        }
    },

    clickIndexAreaId: function (areaId, areaName) {
        $("#index_area_id_btn").html(`${areaId}-${areaName} <span class="caret"></span>`);
        sessionStorage.setItem(ApiConfig.SESSION_INDEX_AREA_ID_NAME, areaId + "-" + areaName);
        sessionStorage.setItem(ApiConfig.SESSION_INDEX_AREA_ID, areaId);
        MainPage.current.attr("src", ApiConfig.DASHBOARD_ZDO);
        if ($("#search_appId")) {
            init_app_id_sbox("search_appId", null, false);
        }
    }

};
IndexMgr.init();
